package com.unionpay.main;

import java.io.File;

import com.unionpay.tool.Files;
import com.unionpay.tool.Shell;

/**
 * 用shell脚本搜索出路径下所有的apk文件
 * 
 * @author liuzy
 */
public class SearchApk {
	public static final String SHELL_FILE = "FindLastApk_Shell.sh";
	public static final String RSULT_FILE = "FindLastApk_List.txt";

	public static void search(String path) {
		FindLastApk.print("扫描目录:" + path);
		File resultFile = new File(FindLastApk.WORK + "/" + RSULT_FILE);
		if (resultFile.exists()) {
			FindLastApk.print("扫描结果文件已存在.");
			return;
		}
		File shellFile = new File(FindLastApk.WORK + "/" + SHELL_FILE);
		if (shellFile.exists()) {
			FindLastApk.print("脚本已存在.");
		} else {
			FindLastApk.print("创建脚本...");
			Files.writeFile(createShell(), shellFile);
		}
		FindLastApk.print("添加执行权限...");
		Shell.execute("chmod +x " + SHELL_FILE);
		FindLastApk.print("执行脚本...");
		Shell.execute("sh " + SHELL_FILE + " " + path);
		FindLastApk.print("删除脚本...");
		shellFile.delete();
	}

	public static String createShell() {
		StringBuffer sb = new StringBuffer();
		sb.append("#!/bin/bash\n");
		sb.append("\n");
		sb.append("WORK=`pwd`\n");
		sb.append("\n");
		sb.append("function foreach()\n");
		sb.append("{\n");
		sb.append("        for file in `ls $1`\n");
		sb.append("        do\n");
		sb.append("                if [ -d $1'/'$file ] ; then\n");
		sb.append("                        foreach $1'/'$file'/'\n");
		sb.append("                else\n");
		sb.append("                        FILEPATH=$1$file\n");
		sb.append("                        if [[ $FILEPATH = *.apk ]] ; then\n");
		sb.append("                                echo $FILEPATH >> $WORK/" + RSULT_FILE + "\n");
		sb.append("                        fi\n");
		sb.append("                fi\n");
		sb.append("        done\n");
		sb.append("}\n");
		sb.append("\n");
		sb.append("if [ ! $1 ] ; then\n");
		sb.append("        echo 'Input A Dictionary!'\n");
		sb.append("        exit 0\n");
		sb.append("fi\n");
		sb.append("\n");
		sb.append("foreach $1/\n");
		sb.append("\n");
		sb.append("sed -i 's/\\/\\//\\//g' " + RSULT_FILE + "\n");
		return sb.toString();
	}
	
}

/* Shell代码
#!/bin/bash

WORK=`pwd`

function foreach()
{
        for file in `ls $1`
        do
                if [ -d $1'/'$file ] ; then
                        foreach $1'/'$file'/'
                else
                        FILEPATH=$1$file
                        if [[ $FILEPATH = *.apk ]] ; then
                                echo $FILEPATH >> $WORK/result.txt
                        fi
                fi
        done
}

if [ ! $1 ] ; then
        echo "Input A Dictionary!"
        exit 0
fi

foreach $1/

sed -i 's/\/\//\//g' result.txt
*/